#include <stdio.h>
#include "argtable3/argtable3.h"
#include "esp_console.h"
#include "esp_log.h"

static const char *TAG = "console_i2ctools";

static struct {
    struct arg_str *ssid;
    struct arg_str *password;
    struct arg_end *end;
} wifi_config_args;


static struct {
    struct arg_str *url;
    struct arg_int *port;
    struct arg_end *end;
} mqtt_config_args;



static int do_set_wifi_config_cmd(int argc, char **argv)
{
    int nerrors = arg_parse(argc, argv, (void **)&wifi_config_args);
    if (nerrors != 0) {
        arg_print_errors(stderr, wifi_config_args.end, argv[0]);
        return 0;
    }

    ESP_LOGI(TAG, "%s SSID:%s PWD:%s\r\n", __func__, (char *)wifi_config_args.ssid->sval[0], wifi_config_args.ssid->sval[0]);
    return 0;
}

static void register_wifi_set_cconfig(void)
{
    wifi_config_args.ssid = arg_str0(NULL, "ssid", "<string>", "Set the WIFI SSID");
    wifi_config_args.password = arg_str1(NULL, "password", "<string>", "Set the WIFI PASSWORD");
    wifi_config_args.end = arg_end(2);
    const esp_console_cmd_t wifi_get_config_cmd = {
        .command = "wifi_set",
        .help = "Config set wifi",
        .hint = NULL,
        .func = &do_set_wifi_config_cmd,
        .argtable = &wifi_config_args
    };
    ESP_ERROR_CHECK(esp_console_cmd_register(&wifi_get_config_cmd));
}


static int do_set_mqtt_config_cmd(int argc, char **argv)
{
    int nerrors = arg_parse(argc, argv, (void **)&mqtt_config_args);
    if (nerrors != 0) {
        arg_print_errors(stderr, mqtt_config_args.end, argv[0]);
        return 0;
    }
    ESP_LOGI(TAG, "%s url:%s port:%d\r\n", __func__, (char *)mqtt_config_args.url->sval[0], mqtt_config_args.port->ival[0]);
    return 0;
}

static void register_mqtt_set_cconfig(void)
{
    mqtt_config_args.url = arg_str0(NULL, "url", "<string>", "Set the MQTT url");
    mqtt_config_args.port = arg_int1(NULL, "port", "<int>", "Set the MQTT port");
    mqtt_config_args.end = arg_end(2);
    const esp_console_cmd_t mqtt_get_config_cmd = {
        .command = "mqtt_set",
        .help = "Config set mqtt",
        .hint = NULL,
        .func = &do_set_mqtt_config_cmd,
        .argtable = &mqtt_config_args
    };
    ESP_ERROR_CHECK(esp_console_cmd_register(&mqtt_get_config_cmd));
}

void register_consoletools(void)
{
    register_wifi_set_cconfig();
    register_mqtt_set_cconfig();
}
